package pers.agony.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : Agony
 * @date : Created in 11:15 上午 2021/11/5
 * @Description: 存储用户账户名单
 * @Modified By:
 * @version: : 1.0
 */
public class UserService implements UserDetailsService{
    /**
     * 从数据库查询用户信息
     * 代替<security:user name="admin" authorities="ROLE_ADMIN" password="{noop}admin"/>
     * 必须提供用户名密码和权限集合
     * @param username 从前端来的
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查询用户信息
        pers.agony.pojo.User logUser = map.get(username);
        //查询到数据，返回User，查询不到信息，返回null
        if(logUser == null){
            return null;
        }
        //User(String, String, Collection<? extends GrantedAuthority>)
        List<GrantedAuthority> authorities = new ArrayList<>();
        //认证：通过用户名查询用户信息，查到了以后比较前端密码和数据可密码，通过则认证成功
        //授权：authorities集合，给集合添加元素（权限｜角色名称）绑定到user对象
        // string role
//        authorities.add(new SimpleGrantedAuthority("BBB"));
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        //密码是明文，就要加{noop}，框架会把前端和数据库密码进行校验
        //UserDetail下的user作用：校验密码，校验权限，存入session
        return new User(username,logUser.getPassword(),authorities);
    }


    //模拟数据库中的用户数据
    public static Map<String, pers.agony.pojo.User> map = new HashMap<String, pers.agony.pojo.User>();

    static {
        pers.agony.pojo.User user1 = new pers.agony.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("$2a$10$BA8PaGh.NN/vP7U4Xq0qpesqu/DhVi2dU0.RrOXG//zxc0oIYV4L.");

        pers.agony.pojo.User user2 = new pers.agony.pojo.User();
        user2.setUsername("zhangsan");
        user2.setPassword("123");

        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123");
        System.out.println("encode = " + encode);
        //$2a$10$BA8PaGh.NN/vP7U4Xq0qpesqu/DhVi2dU0.RrOXG//zxc0oIYV4L.

        System.out.println(bCryptPasswordEncoder.matches("123", "$2a$10$BA8PaGh.NN/vP7U4Xq0qpesqu/DhVi2dU0.RrOXG//zxc0oIYV4L."));
    }


}
